// download.js
import { dialog, clipboard, BrowserWindow } from 'electron'
import fs from 'fs'
import axios from 'axios'
import wallpaper from 'wallpaper'
// 引入项目
const { autoUpdater } = require('electron-updater')
const { spawn } = require('child_process')
const path = require('path')
// 配置项
autoUpdater.forceDevUpdateConfig = true //开发环境下强制更新
autoUpdater.autoDownload = false // 自动下载
autoUpdater.autoInstallOnAppQuit = false // 应用退出后自动安装
let isStartCheckForUpdates = false

// 文件下载 currentWindow 当前窗口
export const downloadFileToFolder = (currentWindow: BrowserWindow, downloadUrl: string, fileName: string, savePath: string) => {
    const targetFolder = path.join(savePath)

    // 如果目标文件夹不存在，则创建它
    if (!fs.existsSync(targetFolder)) {
        fs.mkdirSync(targetFolder, { recursive: true })
    }

    const fullFileName = `${fileName}.png`
    const filePath = path.join(targetFolder, fullFileName)
    const stream = fs.createWriteStream(filePath)

    let totalBytes = 0
    let downloadedBytes = 0

    axios({
        method: 'GET',
        url: downloadUrl,
        responseType: 'stream'
    }).then((response) => {
        totalBytes = parseInt(response.headers['content-length'], 10)

        response.data.on('data', (chunk) => {
            downloadedBytes += chunk.length
            // 计算下载进度百分比
            const progress = Math.floor((downloadedBytes / totalBytes) * 100)
            // 只将进度信息发送给当前发起下载请求的窗口的渲染进程
            if (currentWindow) {
                currentWindow.webContents.send('download-progress', progress)
            }
        })

        response.data.pipe(stream)

        return new Promise((resolve, reject) => {
            stream.on('close', () => {
                // 通知渲染进程下载成功
                if (currentWindow) {
                    const obj = {
                        type: 'success',
                        message: '下载成功'
                    }
                    currentWindow.webContents.send('download-complete', obj)
                    resolve(true)
                }
                // 通知渲染进程下载成功 (所有窗口)
                // BrowserWindow.getAllWindows().forEach((window) => {
                //     const obj = {
                //         type: 'success',
                //         message: '下载成功'
                //     }
                //     window.webContents.send('download-complete', obj)
                //     resolve(true)
                // })
            })

            stream.on('error', (err) => {
                stream.close()
                // 通知渲染进程下载失败
                if (currentWindow) {
                    const obj = {
                        type: 'error',
                        message: '下载失败'
                    }
                    currentWindow.webContents.send('download-complete', obj)
                    reject(err)
                }
            })
        })
    }).catch((_) => {
        stream.close()
        // 通知渲染进程下载失败
        if (currentWindow) {
            const obj = {
                type: 'error',
                message: '下载失败'
            }
            currentWindow.webContents.send('download-complete', obj)
        }
    })
}

// 选取本地文件路径
export const selectLocalFilePath = () => {
    // 打开文件夹选择对话框
    return dialog.showOpenDialog({
        properties: ['openDirectory']
    })
}

// 获取文件夹中的所有图片地址
export const getAllImageUrls = (folderPath: string) => {
    const imageUrls: string[] = []
    const files = fs.readdirSync(folderPath)
    files.forEach(file => {
        const filePath = path.join(folderPath, file)
        const fileStat = fs.statSync(filePath)
        if (fileStat.isFile() && /\.(jpg|jpeg|png|gif|bmp)$/i.test(file)) {
            imageUrls.push(`file://${filePath}`)
        }
    })
    return imageUrls
}

// 复制到剪贴板
export const copyTextToClipboard = (imageUrl: string) => {
    clipboard.writeText(imageUrl)
}

// 检查更新
export const checkForUpdates = (url: string) => {
    return new Promise((resolve, reject) => {
        if (isStartCheckForUpdates) {
            reject(new Error('更新检查已在进行中'))
            return
        }
        isStartCheckForUpdates = true

        // 指定更新地址
        autoUpdater.setFeedURL(url)
        autoUpdater.autoDownload = false
        autoUpdater.checkForUpdates()

        // 开始检查更新事件  提示语: '正在检查更新'
        autoUpdater.on('checking-for-update', function () {
        })

        // 发现可更新版本  提示语: 检测到新版本，准备下载
        autoUpdater.on('update-available', function (e) {
            // 这里获取新版本信息，具体获取方式取决于autoUpdater的实现
            // 假设它有一个方法可以获取到新版本的详细信息对象，比如版本号、更新内容等
            isStartCheckForUpdates = false
            resolve(e)
        })

        // 没有可更新版本事件  提示语: '已经是最新版本'
        autoUpdater.on('update-not-available', function () {
            isStartCheckForUpdates = false
            resolve(null)
        })

        // 更新发生错误时事件  提示语: '软件更新异常,请重试'
        autoUpdater.on('error', function () {
            isStartCheckForUpdates = false
            reject(new Error('软件更新异常，请重试'))
        })
    })
}

// 软件下载
export const downloadSoftware = (currentWindow: BrowserWindow, downloadUrl: string, fileName: string, savePath: string) => {
    const targetFolder = path.join(savePath)
    if (!fs.existsSync(targetFolder)) {
        fs.mkdirSync(targetFolder, { recursive: true })
    }
    const stream = fs.createWriteStream(path.join(targetFolder, fileName))

    let totalBytes = 93 * 1024 * 1024 // 手动指定文件大小为93MB
    let downloadedBytes = 0

    axios({
        method: 'GET',
        url: downloadUrl,
        responseType: 'stream'
    }).then((response) => {

        response.data.on('data', (chunk) => {
            downloadedBytes += chunk.length
            let progress = Math.floor((downloadedBytes / totalBytes) * 100)
            // 只通知当前窗口
            if (currentWindow) {
                if (progress > 100) progress = 100
                currentWindow.webContents.send('download-progress', progress)
            }
        })

        response.data.pipe(stream)

        return new Promise((resolve, _) => {
            stream.on('close', () => {
                if (currentWindow) {
                    const obj = {
                        type: 'success',
                        message: '下载成功'
                    }
                    currentWindow.webContents.send('download-complete', obj)
                    resolve(true)
                }

                // 下载成功后 安装软件
                installSoftware(currentWindow, path.join(targetFolder, fileName))
            })

            stream.on('error', (err) => {
                stream.close()
                if (currentWindow) {
                    const obj = {
                        type: 'error',
                        message: '下载失败' + err
                    }
                    currentWindow.webContents.send('download-complete', obj)
                    resolve(true)
                }
            })
        })
    }).catch((_) => {
        stream.close()
        // 通知渲染进程下载失败
        if (currentWindow) {
            const obj = {
                type: 'error',
                message: '下载失败'
            }
            currentWindow.webContents.send('download-complete', obj)
        }
    })
}

// 安装软件函数
const installSoftware = (currentWindow: BrowserWindow, filePath: string) => {
    // 判断是否为Windows可执行文件（.exe）
    const ext = path.extname(filePath)
    if (ext === '.exe') {
        try {
            // 使用 spawn 启动安装程序，以便更好地处理输出和错误信息
            const installerProcess = spawn(filePath, [], { shell: true })

            // 监听安装进程的输出信息，可用于在控制台显示安装进度等相关信息（可选）
            installerProcess.stdout.on('data', (data) => {
                console.log(`安装程序输出: ${data}`)
            })

            // 监听安装进程的错误信息
            installerProcess.stderr.on('data', (data) => {
                console.log(`安装程序错误: ${data}`)
            })

            // 当安装进程结束时
            installerProcess.on('close', (code) => {
                if (code === 0) {
                    const obj = {
                        type: 'success',
                        message: '软件安装成功'
                    }
                    currentWindow.webContents.send('download-complete', obj)
                } else {
                    const obj = {
                        type: 'error',
                        message: '安装失败'
                    }
                    currentWindow.webContents.send('download-complete', obj)
                }
            })
        } catch (err: any) {
            const obj = {
                type: 'error',
                message: `无法执行文件`
            }
            currentWindow.webContents.send('download-complete', obj)
        }
    } else {
        const obj = {
            type: 'error',
            message: '不支持的文件类型，无法安装软件'
        }
        currentWindow.webContents.send('download-complete', obj)
    }
}

// 设置本地图片为壁纸
export const setPictureAsWallpaper = async (Path: string) => {
    try {
        await wallpaper.set(Path)
    } catch (err) {
        console.error('加载wallpaper模块或设置壁纸失败：', err)
    }
}